#!/usr/bin/env python

try:
	import pdb
	import pygame
	import sys
	from pygame.locals import *
	from lib.scenarioengine import *
	import traceback
except ImportError, err:
	print "Could not load %s module." % (err)
	raise SystemExit

MOVEMENT_KEYS = (str(K_UP), str(K_RIGHT), str(K_DOWN), str(K_LEFT))
CANCEL_KEYS = (str(K_BACKSPACE))
ACTION_KEYS = (str(K_RETURN))

def run():

	clock = pygame.time.Clock()

	# init screen
	pygame.init()
	pygame.key.set_repeat(200, 50)
	screen = pygame.display.set_mode((800, 600))
	engine = ScenarioEngine()

	while 1:
		mods = pygame.key.get_mods()
		for event in pygame.event.get():
			try:
				if event.type == QUIT:
					pygame.quit()
					return
				elif event.type == USEREVENT:
					if event.name == 'WINDOW_CLOSED':
						engine.finish_window_close()
						break
				elif event.type == KEYDOWN:
					if event.key == K_ESCAPE:
						pygame.quit()
						return
					elif engine.is_animating():
						break
					elif (event.key) == K_SPACE:
						traceback.print_exc()
					elif str(event.key) in CANCEL_KEYS:
						engine.do_cancel()
					elif str(event.key) in ACTION_KEYS:
						engine.do_action()
					elif str(event.key) in MOVEMENT_KEYS:
						#Use normal move for normal movement - menus etc
						engine.do_move(event.key, mods)

			except Exception:
				print sys.exc_info()

		#print engine.updaterects
		
		engine.draw_layers()
		pygame.display.update(engine.updaterects)
		clock.tick(60)


if __name__ == "__main__":
	run()
#	import profile
#	profile.run('run()')
